from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin, CacheResponseMixin

from .serializers import TagSerializer, ArticleSerializer
from .models import Tag, Article


# 自定义分页对象
class ArticlePagination(PageNumberPagination):
    # 默认的大小
    page_size = 5
    # 页面的最大大小
    max_page_size = 5


class ArticleView(CacheResponseMixin, ReadOnlyModelViewSet):
    ''' 文章 '''
    queryset = Article.objects.all().order_by('-create_time')
    serializer_class = ArticleSerializer

    pagination_class = ArticlePagination

    # 重写父类方法，添加缓存响应头
    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        response['Cache-Control'] = 'max-age=180'
        return response

    # 重写父类方法，添加缓存响应头
    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, *args, **kwargs)
        response['Cache-Control'] = 'max-age=180'
        return response


class TagView(ListCacheResponseMixin, ListAPIView):
    ''' 文章标签 '''
    queryset = Tag.objects.all()
    serializer_class = TagSerializer

    # 重写父类方法，添加缓存响应头
    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        response['Cache-Control'] = 'max-age=180'
        return response
